package com.ruoyi.web.controller.device.keep;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Keeper;
import com.ruoyi.common.core.domain.entity.Report;
import com.ruoyi.common.core.domain.entity.ReportKeeper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SmsTemplateCode;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SmsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.KeepService;
import com.ruoyi.system.service.ReportKeepService;
import com.ruoyi.system.service.ReportService;
import com.ruoyi.system.service.resp.ReportKeeperDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api("查询维保人员指派")
@RestController
@RequestMapping("/device/keep/reportKeep")
public class ReportKeepController extends BaseController {
    @Autowired
    private ReportKeepService reportKeepService;
    @Autowired
    private KeepService KeepService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private ReportService reportService;

    @Log(title = "查询维保人员指派", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(ReportKeeper reportKeeper) {
        startPage();
        List<ReportKeeper> list = reportKeepService.selectKeepList(reportKeeper);
        return getDataTable(fillToDTO(list));
    }


    @Log(title = "查询维保人员指派All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(ReportKeeper reportKeeper) {
        List<ReportKeeper> list = reportKeepService.selectAll(reportKeeper);
        return getDataTable(fillToDTO(list));
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(fillOneToDTO(reportKeepService.selectById(id)));
    }

    @ApiOperation("增加查询维保人员指派")
    @Log(title = "新增维保人员指派", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @RepeatSubmit
    public AjaxResult add(@Validated @RequestBody ReportKeeper keeper) {
        keeper.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = reportKeepService.createKeep(keeper);
//        //给被指派的人发送短信
//        if (keeper.getKeeperId() == null) {
//            throw new BaseException("指派失败,指派人为空");
//        }
//        SysUser sysUser = sysUserMapper.selectUserById(keeper.getKeeperId());
//        if (sysUser == null) {
//            throw new BaseException("指派失败,未查询到指派人" + keeper.getKeeperId());
//        }
//        if (StringUtils.isNotBlank(sysUser.getPhonenumber())) {
//            SmsUtils.sendSms(SmsTemplateCode.DELETED.getCode(), sysUser.getPhonenumber());
//        }
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "修改维保人员指派", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    @RepeatSubmit
    public AjaxResult edit(@Validated @RequestBody ReportKeeper reportKeeper) {
        reportKeeper.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = reportKeepService.updateKeep(reportKeeper);
//        //给被指派的人发送短信
//        SysUser sysUser = sysUserMapper.selectUserById(reportKeeper.getKeeperId());
//        if (sysUser == null) {
//            throw new BaseException("指派失败,未查询到指派人" + reportKeeper.getKeeperId());
//        }
//        if (StringUtils.isNotBlank(sysUser.getPhonenumber())) {
//            SmsUtils.sendSms(SmsTemplateCode.DELETED.getCode(), sysUser.getPhonenumber());
//        }
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "删除维保人员指派", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(reportKeepService.deleteById(id));
    }

    private List<ReportKeeperDTO> fillToDTO(List<ReportKeeper> reportKeepers) {
        if (CollectionUtils.isEmpty(reportKeepers)) {
            return new ArrayList<>();
        }
        List<Long> keeperIds = reportKeepers.stream().map(ReportKeeper::getKeeperId).collect(Collectors.toList());

        Map<Long, Keeper> keeperMap = KeepService.selectByIds(keeperIds).stream().collect(Collectors.toMap(Keeper::getId, g -> g));
        Report report = reportService.selectById(reportKeepers.get(0).getReportId());
        return reportKeepers.stream().map(g -> {
            ReportKeeperDTO reportKeeperDTO = new ReportKeeperDTO();
            reportKeeperDTO.setId(g.getId());
            reportKeeperDTO.setReportId(g.getReportId());
            reportKeeperDTO.setKeeperId(g.getKeeperId());
            reportKeeperDTO.setCreateBy(g.getCreateBy());
            reportKeeperDTO.setCreateTime(g.getCreateTime());
            reportKeeperDTO.setUpdateBy(g.getUpdateBy());
            reportKeeperDTO.setUpdateTime(g.getUpdateTime());
            reportKeeperDTO.setStatus(g.getStatus());
            reportKeeperDTO.setRemark(g.getRemark());
            Keeper keeper = keeperMap.get(g.getKeeperId());
            if (keeper != null) {
                reportKeeperDTO.setKeepName(keeper.getName());
                reportKeeperDTO.setKeepPhone(keeper.getPhone());
            }
            if (report != null) {
                reportKeeperDTO.setCustomerId(report.getCustomerId());
                reportKeeperDTO.setComment(report.getComment());
                reportKeeperDTO.setExtra(report.getExtra());
                reportKeeperDTO.setLocation(report.getLocation());
                reportKeeperDTO.setContent(report.getContent());
                reportKeeperDTO.setBookTime(report.getBookTime());
            }
            return reportKeeperDTO;
        }).collect(Collectors.toList());
    }

    private ReportKeeperDTO fillOneToDTO(ReportKeeper reportKeeper) {
        if (reportKeeper == null) {
            return null;
        }
        ReportKeeperDTO reportKeeperDTO = new ReportKeeperDTO();
        reportKeeperDTO.setId(reportKeeper.getId());
        reportKeeperDTO.setReportId(reportKeeper.getReportId());
        reportKeeperDTO.setKeeperId(reportKeeper.getKeeperId());
        reportKeeperDTO.setCreateBy(reportKeeper.getCreateBy());
        reportKeeperDTO.setCreateTime(reportKeeper.getCreateTime());
        reportKeeperDTO.setUpdateBy(reportKeeper.getUpdateBy());
        reportKeeperDTO.setUpdateTime(reportKeeper.getUpdateTime());
        reportKeeperDTO.setRemark(reportKeeper.getRemark());
        Keeper keeper = KeepService.selectById(reportKeeper.getId());
        if (keeper != null) {
            reportKeeperDTO.setKeepName(keeper.getName());
            reportKeeperDTO.setKeepPhone(keeper.getPhone());
        }
        return reportKeeperDTO;
    }

}
